import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication


class EmailUtil:

    smtp_server = "smtp.qq.com"  # SMTP服务器地址，例如QQ邮箱
    smtp_port = 465  # SSL端口一般是465\587
    sender_email = "ppt85@foxmail.com"
    sender_password = "wffpenmrynpubdae"  # 注意是邮箱的授权码，不是登录密码

    html = True,


    @classmethod
    def send_email(
            cls,
            receiver_email: str,
            subject: str,
            body: str,
            html: bool = False,
            attachments: list[str] = None,
    ):
        try:
            # 构造邮件
            msg = MIMEMultipart()
            msg["From"] = cls.sender_email
            msg["To"] = receiver_email
            msg["Subject"] = subject

            # 添加正文（支持纯文本 / HTML）
            if html:
                msg.attach(MIMEText(body, "html", "utf-8"))
            else:
                msg.attach(MIMEText(body, "plain", "utf-8"))

            # 添加附件
            if attachments:
                for file_path in attachments:
                    with open(file_path, "rb") as f:
                        part = MIMEApplication(f.read())
                        part.add_header("Content-Disposition", "attachment", filename=file_path.split("/")[-1])
                        msg.attach(part)

            # 连接服务器并发送
            with smtplib.SMTP_SSL(cls.smtp_server, cls.smtp_port) as server:  # 如果不用SSL，可以改成 SMTP()
                server.login(cls.sender_email, cls.sender_password)
                server.sendmail(cls.sender_email, receiver_email, msg.as_string())
                server.quit()

            print("✅ 邮件发送成功")

        except Exception as e:
            print("❌ 邮件发送失败:", e)

